<template>
    <div class="table">
        <div class="container">
            <div class="handle-box">
                <el-form ref="form" label-width="100px">
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="用户">
                                <el-select placeholder="请选择用户" style="width: 90%" v-model="form.dbUser"
                                           filterable @change="dbUserChange">
                                    <el-option v-for="item in dics.dbUser"
                                               :key="item.dbId+'-'+item.dbUser"
                                               :label="item.dbNotes"
                                               :value="item.dbId+'-'+item.dbUser"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="表类型">
                                <el-select placeholder="请选择表类型" style="width: 90%" v-model="form.tabType"
                                           clearable filterable @change="tabTypeChange">
                                    <el-option v-for="item in dics.tabType"
                                               :key="item.dict_code"
                                               :label="item.dict_name"
                                               :value="item.dict_code"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="表名">
                                <el-input v-model="form.tabName" placeholder="请输入表名" class="handle-input mr10"
                                          style="width: 90%"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col align="center">
                            <el-button type="primary" icon="el-icon-search" @click="search" style="width: 100px">
                                查询
                            </el-button>
                            <el-button type="primary" icon="el-icon-refresh" @click="refresh"
                                       style="width: 100px;margin-left: 20px;">
                                刷新
                            </el-button>
                            <el-button type="primary" icon="el-icon-lx-favor" @click="checkGen()"
                                       style="width: 100px;margin-left: 20px;">
                                一键生成
                            </el-button>
                            <el-button type="primary" icon="el-icon-lx-down" @click="allDownload"
                                       style="width: 100px;margin-left: 20px;">
                                一键下载
                            </el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <ces-table ref="cestable" :that='that' size='small'
                       :tableHeight='tableHeight'
                       :stripe="true"
                       :isIndex='true'
                       :isHandle='true'
                       :isSelection='false'
                       :radioSelection='true'
                       :isPagination='false'
                       :tableData='tableData'
                       :tableCols='tableCols'
                       :tablePage='pagination'
                       @handleSelectionChange='handleSelectionChange'
                       @handleCurrentChange='handleCurrentChange'
                       @handleSizeChange="handleSizeChange">
            </ces-table>
            <!--生成代码选择路径的对话框-->
            <el-dialog title="提示"
                       :visible="file.dialogVisible"
                       width="50%"
                       :before-close="handleClose">
                <el-form :model="file" ref="fileForm" :rules="rules" style="margin-top: -30px;">
                    <el-row>
                        <el-form-item label="前端代码路径" prop="webPath">
                            <input type="file" id="webPath" webkitdirectory hidden @change="fileChange('web')"></input>
                            <el-input v-model="file.webPath" placeholder="请选择保存前端代码的路径" class="handle-input mr10"
                                      style="width:70%;display: flex;">
                                <el-button slot="append" icon="el-icon-lx-file" style="line-height: 32px;"
                                           @click="fileClick('web')"></el-button>
                            </el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="后端代码路径" prop="javaPath">
                            <input type="file" id="javaPath" webkitdirectory directory hidden
                                   @change="fileChange('java')"></input>
                            <el-input v-model="file.javaPath" placeholder="请选择保存后端代码的路径" class="handle-input mr10"
                                      style="width: 70%;display: flex;">
                                <el-button slot="append" icon="el-icon-lx-file" style="line-height: 32px;"
                                           @click="fileClick('java')"></el-button>
                            </el-input>
                        </el-form-item>
                    </el-row>
                    <el-row style="text-align: center;">
                        <el-button @click="handleClose">取 消</el-button>
                        <el-button type="primary" v-show="file.butType==1" @click="generate('fileForm')">确 定</el-button>
                        <el-button type="primary" v-show="file.butType==2" @click="allGenerate('fileForm')">确 定
                        </el-button>
                    </el-row>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import cesTable from '@cores/commons/main/Table'

    export default {
        name: "",
        components: {
            cesTable,
        },
        data() {
            return {
                that: this,
                tableHeight: window.innerHeight - 325,
                url_pageDb: '/little-base-generator/generator/db/selectDb',//查询数据源
                url_pageTab: '/little-base-generator/generator/tabCol/queryTab',//查询表
                url_pageDep: '/little-base-generator/generator/gen/queryDep',//查询配置
                url_download: '/little-base-generator/generator/gen/genCodeDownload',//下载
                url_inArea: '/little-base-generator/generator/gen/genCodeInArea',//生成
                url_allDownload: '/little-base-generator/generator/gen/genCodeAllDownload',//一键下载
                url_allInArea: '/little-base-generator/generator/gen/genCodeAllInArea',//一键生成
                multipleSelection: [],
                // 表头及字段
                tableCols: [
                    {label: '用户', align: 'center', prop: 'dbUser'},
                    {label: '表类型', align: 'center', prop: 'tabType', width: 100},
                    {label: '表名', align: 'center', prop: 'tabName'},
                    {label: '表注释', align: 'center', prop: 'tabNotes'},
                    {
                        label: '操作', fixed: 'right', align: 'center', type: 'Button', width: 220,
                        btnList: [
                            {
                                type: 'text',
                                label: '配置',
                                icon: 'el-icon-lx-skin',
                                handle: (row, that) => this.deploy(row, that)
                            },
                            {
                                type: 'text',
                                label: '生成',
                                icon: 'el-icon-lx-favor',
                                handle: (row, that) => this.checkGen(row, that)
                            },
                            {
                                type: 'text',
                                label: '下载',
                                icon: 'el-icon-lx-down',
                                handle: (row, that) => this.download(row, that)
                            },
                            /*{
                                type: 'text',
                                label: '预览',
                                icon: 'el-icon-lx-searchlist',
                                handle: (row, that) => this.preview(row, that)
                            },*/
                        ]
                    },
                ],
                tableData: [],//表格数据
                pagination: {
                    pageSize: 10, pageNum: 1, total: 0
                },
                form: {
                    page: '1',//第几页
                    limit: '10',//每页条数，默认10条
                    dbId: '', dbUser: '', tabName: '', tabType: '',
                },
                dics: {dbUser: []},
                file: {dialogVisible: false, row: {}, webPath: '', javaPath: '', butType: ''},
                rules: {
                    webPath: [{required: true, message: " ", trigger: "focus"}],
                    javaPath: [{required: true, message: " ", trigger: "focus"}],
                },
            }
        },
        created() {
            this.initDict();//加载字典
        },
        methods: {
            //变更分页条数
            handleSizeChange(val) {
                this.form.limit = val;
                this.getPages();
            },
            //变更上一页下一页
            handleCurrentChange(val) {
                this.form.page = val;
                this.getPages();
            },
            //选中table行
            handleSelectionChange(val) {
                this.$refs.cestable.clearSelect();
                this.multipleSelection = val;
            },
            /*用户值改变事件*/
            dbUserChange(val) {
                if (val != undefined && val != '' && val != null) {
                    this.getPages();
                } else {
                    this.tableData = [];
                    this.pagination.total = 0;
                }
            },
            /*表类型值改变事件*/
            tabTypeChange(val) {
                this.form.tabType = val;
                this.getPages();
            },
            /*初始化字典*/
            initDict() {
                this.dics.tabType = [
                    {dict_code: 'TABLE', dict_name: 'TABLE'},
                    {dict_code: 'VIEW', dict_name: 'VIEW'},
                ];
                this.$post(this.url_pageDb, {page: 1, limit: 100, dbStatus: '1'}).then(res => {
                    if (res.data) {
                        this.dics.dbUser = res.data.list;
                        this.form.dbUser = this.dics.dbUser[0].dbId + '-' + this.dics.dbUser[0].dbUser;
                        if (this.form.dbUser != undefined && this.form.dbUser != '' && this.form.dbUser != null) {
                            this.getPages();
                        } else {
                            this.tableData = [];
                            this.pagination.total = 0;
                        }
                    }
                })
            },
            // 获取分页数据
            getPages() {
                if (localStorage.getItem('fromDeploy') === "true") {
                    var cache = JSON.parse(localStorage.getItem('newForm'));
                    this.form = cache.form;
                    this.pagination = cache.pagination;
                } else {
                    localStorage.setItem("newForm", JSON.stringify({form: this.form, pagination: this.pagination}));
                }
                this.form.limit = this.pagination.pageSize;
                var newForm = {
                    limit: this.pagination.pageSize,
                    page: this.pagination.pageNum,
                    dbId: this.form.dbUser.split('-')[0],
                    dbUser: this.form.dbUser.split('-')[1],
                    tabName: this.form.tabName,
                    tabType: this.form.tabType,
                };
                localStorage.setItem("fromDeploy", false);
                this.$post(this.url_pageTab, newForm).then(res => {
                    if (res.data) {
                        this.tableData = res.data.list;
                        this.pagination.total = res.data.total;
                    } else {
                        this.$message({type: res.code, message: res.msg});
                    }
                })
            },
            //刷新
            refresh() {
                this.$refs.cestable.clearRadioSelection();
                this.multipleSelection = [];
                this.pagination = {pageSize: 10, pageNum: 1, total: 0};
                this.form = {
                    page: '1', limit: '10',
                    dbId: '', dbUser: '', tabName: '', tabType: '',
                };
                this.initDict();
            },
            /*查询*/
            search() {
                this.$refs.cestable.clearRadioSelection();
                this.multipleSelection = [];
                if (this.form.dbUser != undefined && this.form.dbUser != '' && this.form.dbUser != null) {
                    this.getPages();
                } else {
                    this.tableData = [];
                    this.pagination.total = 0;
                }
            },
            /*配置*/
            deploy(index, row) {
                let tagsList = this.$parent.$children[2].tagsList;
                for (let i = 0; i < tagsList.length; i++) {
                    //判断路由是否已经打开
                    if (tagsList[i].path === '/codeDeploy') {
                        tagsList.splice(i, 1)[0];
                    }
                }
                row.dbId = this.form.dbUser.split('-')[0];
                localStorage.setItem("codeDeploy", JSON.stringify(row));
                this.$router.replace({name: 'codeDeploy'});
            },
            /*生成对话框*/
            checkGen(index, row) {
                if (index == undefined) {
                    this.file.butType = 2;
                } else {
                    this.file.butType = 1;
                    this.file.row = row;
                }
                this.file.dialogVisible = true;
            },
            /*保存选择文件路径*/
            fileChange(type) {
                var file = '';
                try {
                    if (type == 'web') {
                        file = document.getElementById('webPath');
                        if (file == null) return;
                        this.file.webPath = file.files[0].value;
                    } else if (type == 'java') {
                        file = document.getElementById('javaPath');
                        this.file.javaPath = file.files[0].value;
                    }
                } catch (e) {
                    //
                }
            },
            /*打开选择文件框*/
            fileClick(type) {
                var file = '';
                if (type == 'web') {
                    file = document.getElementById('webPath');
                } else if (type == 'java') {
                    file = document.getElementById('javaPath');
                }
                file.click();
            },
            /*生成*/
            generate(fileForm) {
                this.$refs[fileForm].validate(valid => {
                    if (valid) {
                        var depForm = {
                            dbId: this.form.dbUser.split('-')[0],
                            tabName: this.file.row.tabName,
                        };
                        var depNewForm = {
                            tabCol: JSON.stringify(depForm),
                            webPath: this.file.webPath + "",
                            javaPath: this.file.javaPath + "",
                        };
                        this.$post(this.url_pageDep, depForm).then(res => {
                            var map = res.data;
                            if (map.colList.length > 0 && map.pro.depProModule != null) {
                                this.$post(this.url_inArea, depNewForm).then(res => {
                                    this.$message({type: res.code, message: res.msg});
                                })
                            } else {
                                this.$message({type: 'fail', message: '请先配置以后再生成'});
                            }
                        })
                        this.handleClose();
                    } else {
                        this.$alert('您有必填项未填写，请确认！', '系统提示', {confirmButtonText: '确定'});
                    }
                })
            },
            /*一键生成*/
            allGenerate() {
                this.$refs.fileForm.validate(valid => {
                    if (valid) {
                        var depForm = {
                            tabCol: JSON.stringify({dbId: this.form.dbUser.split('-')[0]}),
                            webPath: this.file.webPath,
                            javaPath: this.file.javaPath,
                        };
                        this.$post(this.url_allInArea, depForm).then(res => {
                            this.$message({type: res.code, message: res.msg});
                        })
                        this.handleClose();
                    } else {
                        this.$alert('您有必填项未填写，请确认！', '系统提示', {confirmButtonText: '确定'});
                    }
                })
            },
            /*下载*/
            download(index, row) {
                var depForm = {
                    dbId: this.form.dbUser.split('-')[0],
                    tabName: row.tabName,
                };
                this.$post(this.url_pageDep, depForm).then(res => {
                    var map = res.data;
                    if (map.colList.length > 0 && map.pro.depProModule != null) {
                        this.$file_export(this.url_download, depForm).then(res => {
                            if (res) {
                                const content = res;
                                const blob = new Blob([content], {type: "application/zip"});
                                if (blob.size > 0) {
                                    var timestamp = (new Date()).valueOf();
                                    const fileName = timestamp + '.zip';
                                    if ('download' in document.createElement('a')) { // 非IE下载
                                        const elink = document.createElement('a');
                                        elink.download = fileName;
                                        elink.style.display = 'none';
                                        elink.href = window.URL.createObjectURL(blob);
                                        document.body.appendChild(elink);
                                        elink.click();
                                        window.URL.revokeObjectURL(elink.href); // 释放URL 对象
                                        document.body.removeChild(elink);
                                    } else { // IE10+下载
                                        navigator.msSaveBlob(blob, fileName);
                                    }
                                } else {
                                    this.$message({type: 'fail', message: '代码生成下载失败'});
                                }
                            }
                        })
                    } else {
                        this.$message({type: 'fail', message: '请先配置以后再下载'});
                    }
                })
            },
            /*一键下载*/
            allDownload() {
                var depForm = {
                    dbId: this.form.dbUser.split('-')[0],
                };
                this.$file_export(this.url_allDownload, depForm).then(res => {
                    if (res) {
                        const content = res;
                        const blob = new Blob([content], {type: "application/zip"});
                        if (blob.size > 0) {
                            var timestamp = (new Date()).valueOf();
                            const fileName = timestamp + '.zip';
                            if ('download' in document.createElement('a')) { // 非IE下载
                                const elink = document.createElement('a');
                                elink.download = fileName;
                                elink.style.display = 'none';
                                elink.href = window.URL.createObjectURL(blob);
                                document.body.appendChild(elink);
                                elink.click();
                                window.URL.revokeObjectURL(elink.href); // 释放URL 对象
                                document.body.removeChild(elink);
                            } else { // IE10+下载
                                navigator.msSaveBlob(blob, fileName);
                            }
                        } else {
                            this.$message({type: 'fail', message: '代码生成下载失败'});
                        }
                    }
                })
            },
            /*预览*/
            preview(index, row) {
                let tagsList = this.$parent.$children[2].tagsList;
                for (let i = 0; i < tagsList.length; i++) {
                    //判断路由是否已经打开
                    if (tagsList[i].path === '/codePreview') {
                        tagsList.splice(i, 1)[0];
                    }
                }
                localStorage.setItem("codePreview", JSON.stringify(row));
                this.$router.replace({name: 'codePreview'});
            },
            /*关闭对话框*/
            handleClose() {
                this.file.dialogVisible = false;
                this.file = {dialogVisible: false, row: {}, webPath: '', javaPath: '', butType: ''};
            },
        },
    }
</script>

<style scoped>
    @import '../../../../assets/css/common.css';
</style>

